package com.demo.grammar.java14;

import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemoryHandles;
import jdk.incubator.foreign.MemorySegment;


import java.lang.invoke.VarHandle;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;

/**
 * @author novel
 * @date 2021/5/27 15:06
 */
public class MemorySegmentTest {
    public static void main(String[] args) {
//        // 分配 200B 堆外内存
//        MemorySegment memorySegment = MemorySegment.allocateNative(200);
//
//        // 用 ByteBuffer 分配，然后包装为 MemorySegment
//        MemorySegment memorySegment = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
//
//        // MMAP 当然也可以
//        MemorySegment memorySegment = MemorySegment.mapFromPath(Path.of("/tmp/memory.txt"), 200, FileChannel.MapMode.READ_WRITE);
//
//        // 获取堆外内存地址
//        MemoryAddress address = MemorySegment.allocateNative(100).baseAddress();
//
//        // 组合拳，堆外分配，堆外赋值
//        long value = 10;
//        MemoryAddress memoryAddress = MemorySegment.allocateNative(8).baseAddress();
//        // 获取句柄
//        VarHandle varHandle = MemoryHandles.varHandle(long.class, ByteOrder.nativeOrder());
//        varHandle.set(memoryAddress, value);
//
//        // 释放就这么简单，想想 DirectByteBuffer 的释放……多奇怪
//        memorySegment.close();
    }
}
